<?php
namespace app\common\adapter;
class AuthAdapter {
	use \app\common\model\TreeBase;

	protected static $_ruleslist=null;


	public function updateRuleList(){
		$data=db('admin_rule')->where('status',1)->field(['id','name','pid'])->select();
		$data=$this->makeTree($data);
		$data=$this->dealTreeAsList($data);
		if (!cache('AUTH_RULE_LIST',$data,config('cache_param.auth_rule_list'),'AUTH_RULE_LIST')){
			\think\facade\Log::record('写入权限列表缓存失败','warning');
		}
		return $data;
	}

	public static function getRuleList() {
		if (!AuthAdapter::$_ruleslist) {
			AuthAdapter::$_ruleslist = cache('AUTH_RULE_LIST');
		}
		if (!AuthAdapter::$_ruleslist) {
			$adapter=new AuthAdapter();
			AuthAdapter::$_ruleslist = $adapter->updateRuleList();
		}
		return AuthAdapter::$_ruleslist;
	}

	/**
	* check whether the user has permisson to do operate
	*
	* @param <type> $ruleName
	* @param <type> $userInfo
	*
	* @return <type>
	*/
	public static function checkRule($ruleName,$userInfo){
		if (!$userInfo)
			return false;
		if (!$_ruleslist = AuthAdapter::getRuleList()) {
			\think\facade\Log::record('获取列表缓存失败','warning');
			return false;
		}

		if (array_key_exists($ruleName,$_ruleslist)){
			$gidskey=$userInfo['gidkeys'];

			if (!($userRule=cache("GROUP_ACCESS_".$gidskey))) {
				$group = model('admin/Group');
				$userRule=$group->getRulesList($gidskey,$userInfo['gids']);
			}
			$ruleRequire=$_ruleslist[$ruleName];

			if (count($ruleRequire)==count(array_intersect($ruleRequire,$userRule)))
				return true;
		}

		return false;
	}

  /**
   * this function will foreach the whole tree,and concat the 'name' element
   *
   * @param <type> $data
   * @param <type> $cur_string
   * @param <type> $result
   *
   * @return <type>
   */
	protected function dealTreeAsList($data,&$result=[],$cur_string='',$cur_rule_set=[]){
		if (is_array($data)){
			if (array_key_exists('child',$data)){
				if (is_array($data['child'])){
					foreach ($data['child'] as $child)
						if ($child)
							$this->dealTreeAsList($child,$result,$cur_string.$data['name'].'.',array_merge($cur_rule_set,[$data['id']]));
				} else
					$result[$cur_string.$data['name']]=array_merge($cur_rule_set,[$data['id']]);
			} else {
				foreach ($data as $child)
					$this->dealTreeAsList($child,$result,$cur_string,$cur_rule_set);
			}
		}
		return $result;
	}
}